package com.xlf.config;

import com.xlf.filter.JwtAuthenticationTokenFilter;
import com.xlf.service.impl.AccessDeniedHandlerImpl;
import com.xlf.service.impl.AuthenticationEntryPointImpl;
import com.xlf.service.impl.LLSFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * 使用SpringSecurity进行权限认证的校验
 */

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    AuthenticationEntryPointImpl authenticationEntryPoint;

    @Autowired
    AccessDeniedHandlerImpl accessDeniedHandler;

    @Autowired
    LLSFailureHandler failureHandler;

    @Resource
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    /**
     * 权限校验配置
     * @param http          HttpSecurity对象
     * @return              SecurityFilterChain过滤器链
     * @throws Exception    可能抛出的异常
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
                http
                .csrf().disable()       //关闭csrf
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 不通过Session获取SecurityContext
                .and()
                .authorizeRequests()
                .antMatchers(           // 放行Knife4j接口文档
                        "/doc.html",
                        "/webjars/**",
                        "/v3/api-docs/**"
                ).permitAll()
                .antMatchers("/user/login","/user/captcha","/user/add").permitAll()   // 对于登录接口 允许匿名访问(认证过了，有token就不能访问)
                .antMatchers("/user/logout","/file/userAvatar").permitAll()
                        .antMatchers("/realOrderTime/**").permitAll()
                        .antMatchers("/foodPricutre/**","/userAvatar/**").permitAll()   // 静态资源
                        .antMatchers("/client/**").permitAll()                            // 小程序端api
                        .antMatchers("/client/me").authenticated()                        // 用户“我的”需要认证
                .anyRequest().authenticated();                                              // 除上面外的所有请求全部需要鉴权认证
//                        .antMatchers("/**").permitAll();  // 临时允许所有请求

        http.formLogin()
//                .successHandler(successHandler)   // 配置认证成功处理器
                .failureHandler(failureHandler);    // 配置认证失败处理器

        // 把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 配置异常处理器
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);

        // 允许跨域
        http.cors();
        return http.build();
    }

    @Resource
    private AuthenticationConfiguration authenticationConfiguration;

    /**
     * 将认证管理器Bean暴露给Spring，用于后续账户密码登录的验证
     * @return              认证管理器对象
     * @throws Exception    可能抛出的异常
     */
    @Bean
    public AuthenticationManager authenticationManager() throws Exception{
        AuthenticationManager authenticationManager = authenticationConfiguration.getAuthenticationManager();
        return authenticationManager;
    }

}